package com.ruoyi.file.component;


import com.alibaba.fastjson2.JSON;
import com.rabbitmq.client.Channel;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.config.RabbitMqConstant;
import com.ruoyi.file.domain.FileConvertorMessage;
import com.ruoyi.file.domain.TblFile;
import com.ruoyi.file.service.ITblFileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;


@Configuration
public class FileConvertorFinishMqListenerConfig {
    Logger logger = LoggerFactory.getLogger(FileConvertorFinishMqListenerConfig.class);
    @Autowired
    private ITblFileService tblFileService;


    /**
     * 消费工作流 业务编码 5011
     *
     * @param channel
     * @param message
     * @return
     * @throws Exception
     */
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(name = RabbitMqConstant.EXCHANGE_FILE_CONVERTOR_FINISH, type = "fanout", durable = "true", autoDelete = "false"),
            key = {RabbitMqConstant.ROUTING_KEY_FILE_CONVERTOR_FINISH},
            value = @Queue(value = RabbitMqConstant.TOPIC_FILE_CONVERTOR_FINISH, durable = "true", exclusive = "false", autoDelete = "false")))
    public void fileConverterMq(String msg, Channel channel, Message message) throws Exception {
        try {
            logger.info("接收到了处理文件转成消息.....");
            FileConvertorMessage convertorMessage = JSON.parseObject(msg, FileConvertorMessage.class);
            processConverFinish(convertorMessage);
            // 手动确认
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            logger.info("处理文件转成成功消息完成");
        } catch (Exception e) {
            logger.error("全局异常信息ex={}, StackTrace={}", e.getMessage(), e);
            if (message.getMessageProperties().getRedelivered()) {
                logger.error("消息已处理,请勿重复处理！");
                // 拒绝消息
                channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
            } else {
                //记录日志
                logger.error("消息消费失败处理：{}", e.getMessage());
                //第一个参数为消息的index，第二个参数是是否批量处理，第三个参数为是否让被拒绝的消息重新入队列
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
            }
        }
    }

    public void processConverFinish(FileConvertorMessage convertorMessage) {
        TblFile tblFile = tblFileService.selectTblFileById(convertorMessage.getId());
        if(tblFile==null){
            logger.error("processConverFinish","file  not exit in db...");
            return;
        }
        if(StringUtils.isEmpty(convertorMessage.getConvertedBucket())
                ||StringUtils.isEmpty(convertorMessage.getConvertedObjectName())){
            logger.error("processConverFinish","file  converted error ...");
            return;
        }
        tblFile.setConverted(1);//
        tblFile.setConvertStartTime(convertorMessage.getConvertStartTime());
        tblFile.setConvertEndTime(convertorMessage.getConvertEndTime());
        tblFile.setConvertedBucket(convertorMessage.getConvertedBucket());
        tblFile.setConvertedType(convertorMessage.getConvertedType());
        tblFile.setConvertedName(convertorMessage.getConvertedName());
        tblFile.setConvertedObjectName(convertorMessage.getConvertedObjectName());
        tblFileService.updateTblFile(tblFile);
    }

}
